<?php

class rf_db_mysql
{
    /**
     * 表名
     *
     * @var string
     */
    public $table       = '';
    /**
     * 表的字段
     *
     * @var string
     */
    public $tableFields = null;

    /**
     * 条件
     *
     * @var string
     */
    public $condition   = '';
    /**
     * 字段
     *
     * @var string
     */
    public $fields      = '*';
    /**
     * 所取的数据库中数据的条数
     * 
     * @var string
     */
    public $limit       = '';

    /**
     * 数据库句柄
     * @var handle
     */
    static $dbhandle    = null;
    /**
     * 数据资源
     *
     * @var resource
     */
    public $result;
    /**
     * 构造函数
     *
     */
    function __construct()
    {
        if (empty($this->tableFields))
        {
            $cacheFile = CACHE_PATH . DS . 'mysqltable' . DS . $this->table . '.php';
            if (is_file($cacheFile))
            {
                require($cacheFile);
            }
            else
            {
                $fields = $this->_showFields();
                $this->tableFields;
            }
        }
        echo 'done';
    }

    /**
     * 查询当前表的字段
     *
     * @TODO 完成
     */
    public function _showFields()
    {
        $sql = "SHOW FIELDS FROM {$this->table}";
        $this->_query($sql);
        $fields = $this->fetch();
        rf::dump($fields);
    }

    /**
     * 指定操作条件
     *
     */
    function setCondition($conditions = '')
    {
        $realCondition = array();
        if (!empty($conditions))
        {
        	if (is_array($conditions))
            {
            	foreach ($conditions as $key => $rowset)
            	{
            		if (is_array($rowset) && count($rowset)>0)
            		{
            		    $realCondition[] = "`" . $key . "` IN ('" . implode("','",$rowset) . "')";
            		}
            		elseif (is_numeric($key))
            		{
            			$realCondition[] = $rowset;
            		}
            		else
            		{
            			$realCondition[] = "`" . $key . "` = '" . $rowset . "'";
            		}
            	}
            	$this->condition = ' WHERE ' . implode(' AND ' , $realCondition);
            }
            elseif(is_string($conditions))
            {
            	$this->condition = ' WHERE ' . $conditions;
            }
        }
        
        return $this;
    }
    
    /**
     * 设置限制查询条件
     *
     * @param int $offset 偏移
     * @param int $limit  限制条数
     */
    function limit($offset = 0, $limit = 30)
    {
    	if ($start >= 0)
    	{
    		$this->limit = "LIMIT {$offset}, {$limit}";
    	}
    	return $this;
    }

    /**
     * 把数据格式化
     *
     * method 可以是 mysql_fetch_assoc , mysql_fetch_object
     * @param $method
     */
    function fetch($method = 'mysql_fetch_assoc')
    {
        if (!is_resource($this->result))
        {
        	return array();
        }
    	while ($row = $method($this->result))
    	{
    		$rows[] = $row;
    	}
    	return $rows;
    }

    /**
     * 分析建和值
     *
     * @param array $array
     */
    function _parseValues($array)
    {
    	foreach ($array as $key => $value)
    	{
    		$keys[]   = $key;
    		$values[] = $value;
    	}
    	$rkeys   = "`" . implode("`,`",$keys) . "`";
    	$rvalues = "'" . implode("','",$values) . "'";
    	return array('fields' => $rkeys,'values' => $rvalues);
    }
    
    /**
     * 分析建和值
     *
     * @param array $array
     */
    function _parseKeysValues($array)
    {
    	foreach ($array as $key => $value)
    	{
    		$rows[] = "`{$key}` = '{$value}'";
    	}
    	
    	return implode(' AND ',$rows);
    }

    /**
     * 查询
     *
     * @param string $sql
     */
    function _query($sql, $handle = null)
    {
        if (!$handle)
        {
            if (!self::$dbhandle)
            {
                $dbConfig = rf::getIni('mysql');
                $config   = $dbConfig[PRODUCT_STATUS];
                $this->setHandle(mysql_connect($config['host'], $config['username'], $config['password']));
                mysql_select_db($config['database'], self::$dbhandle);
            }
            $handle = self::$dbhandle;
        }
    	$this->result = mysql_query($sql,$handle);
    }

    /**
     * 设置句柄
     *
     */
    function setHandle($handle)
    {
        self::$dbhandle = $handle;
        return $this;
    }

    /**
     * 查询1条
     *
     */
    function find($limit = 0)
    {
        if (!empty($limit))
        {
        	$this->limit(0,$limit);
        }
        $sql = "SELECT {$this->fields} FROM {$this->table} {$this->condition} {$this->limit};";
        $this->_query($sql);
        return $this->fetch();
    }
    /**
     * 插入数据
     *
     * @param array $row
     * @return 
     */
    function create($row = array(), $handle = null)
    {
        if (empty($row))
        {
        	return $this;
        }
        $in  = $this->_parseValues($row);
        $sql = "INSERT INTO {$this->table} ({$in['fields']}) VALUES ({$in['values']});";
        $this->_query($sql);
        return mysql_insert_id($this->handle);
    }

    /**
     * 更新
     *
     * @param array $row
     * @return
     */
    function update($row)
    {
        if (empty($row))
        {
        	return $this;
        }
        $in  = $this->_parseKeyValues($row);
        $sql = "UPDATE {$this->table} SET {$in} {$this->condition} {$this->limit};";
        $this->_query($sql);
        return ;
    }

    /**
     * 删除
     *
     */
    function delete()
    {
        $sql = "DELETE FROM {$this->table} {$this->condition} {$this->limit};";
        $this->_query($sql);
        return ;
    }

}
